var querystring = require("querystring"),
	fs = require("fs"),
	formidable = require("formidable"),
	router = require("./router"); 
var path = require('path');

function start(response) {
  console.log("Request handler 'start' was called.");
  fs.readFile("./view/start.html", "utf8", function (err, data) {
    if (err) {
	  response("File wasn't found");
	}
	response.writeHead(200, {"Content-Type":"text/html"});
    response.write(data);
    response.end();
  });
}

function upload(response, request) {
  console.log("Request handler 'upload' was called.");
  /*fs.unlink('./tmp/test.png', function (err) {
    if (err) throw err;
    console.log('successfully deleted /tmp/hello');
  });
  */
  try {
	  fs.unlink('./tmp/test.png', function (err) {
	     //f (err) throw err;
	      console.log('successfully deleted /tmp/test.png');
	  });
	 
      var testpng = path.resolve('./tmp/test.png'); 
      console.log("path to test.png " + testpng);
	  
	  var form = new formidable.IncomingForm();
	  console.log("about to parse");

	  form.parse(request, function(error, fields, files) {
	  	console.log("temp file path " + files.upload.path);
	    var is = fs.createReadStream(files.upload.path);
	    var os = fs.createWriteStream(testpng);
	    is.pipe(os);
	    is.on('end',function() {
	      fs.unlinkSync(files.upload.path);
	    });	    
		response.writeHead(200, {"Content-Type": "text/html"});
		response.write("received image:<br/>");
		response.write("<img src='/show' />");
		response.end();
	  });
	  
	  console.log("parsing done");
  } catch (err){
      console.log("err" + err);
      response.writeHead(500, {"Content-Type": "text/plain"});
	  response.write(error + "\n");	   
	  response.end();
  }
}


function show(response) {
  console.log("Request handler 'show' was called.");
  fs.readFile("./tmp/test.png", function(error, file) {  	
	if(error) {
	  response.writeHead(500, {"Content-Type": "text/plain"});
	  response.write(error + "\n");
	  response.end();
	} else {	  
	  response.writeHead(200, {"Content-Type": "image/png"});
	  response.write(file, "binary");
	  response.end();
	}
  });
}

exports.start = start;
exports.upload = upload;
exports.show = show;